
var btnCheck = document.getElementById("btnCheck");
var infoDiv = document.getElementById("infoDiv");
var btnAdd = document.getElementById("btnAdd");
var rssName = document.getElementById("rssName");
var rssDes = document.getElementById("rssDescription");
var rssLink = document.getElementById("rssLink");

var request = null;
btnCheck.onclick = checkFeed;
rssLink.onkeyup = resetButton;

function resetButton()
{
    infoDiv.innerHTML = '';
    rssName.value = '';
    rssDes.value = '';
    btnCheck.disabled = false;
    btnAdd.disabled = true;
}

function checkRssField() {
    var regexHtml = /^(https?:\/\/){1}([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w\.-]*)*\/?$/;

    if (rssLink.value.length == 0 || rssLink.value.length > 50)
    {
        rssLink.focus();
        infoDiv.innerHTML = "Vui lòng nhập đường dẫn feed từ 0-50 kí tự.".fontcolor("red");
        return false;
    } else if(!regexHtml.test(rssLink.value)){
        rssLink.focus();
        infoDiv.innerHTML =
        "Link feed sai định dạng. Vui lòng bắt đầu bằng: http(s)://......".fontcolor("red");
        return false;
    }
    return true;
}

function checkFeed(e){
    e.preventDefault();
    if (!checkRssField()) {
        return;
    }
    infoDiv.innerHTML = '<img src="img/loading.gif" width="25px"' +
    'height="25px"/> Đang tải thông tin feed.';

    request = new XMLHttpRequest();
    var rssFeedLink = rssLink.value;

    var url = "checkFeed.action?rssLink=" + rssFeedLink;
    request.open("GET", url, true);
    request.onreadystatechange = updateFeedForm;
    request.send(null);
}

function updateFeedForm() {
    if (request.readyState == 4) {
        if (request.status == 200) {
            var result = eval('(' + request.responseText + ')');
            var message = '';

            if (result.message == 'success') {
                rssName.value = result.title ;
                rssDes.value = result.description;
                btnAdd.disabled = false;
                btnCheck.disabled = true;
                message = 'Tải xong thông tin feed';
            } else if (result.message == 'error') {
                message = result.errorInfo.fontcolor("red");
            }
            infoDiv.innerHTML = message;
        }
    }
}
